package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.user.CardUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.user.CardUploadResponse;
import io.renren.common.utils.DateUtil;
import io.renren.common.utils.EmptyUtil;
import io.renren.modules.basedata.dao.UserCardDao;
import io.renren.modules.basedata.entity.Tbl_userCard;
import io.renren.modules.basedata.service.UserCardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class UserCardServiceImpl implements UserCardService {
    private static final Logger log = LoggerFactory.getLogger(UserCardServiceImpl.class);
    @Autowired
    private UserCardDao userCardDao;

    @Override
    public String cardUpload() throws Exception {
        log.info("开始获取未上传客户卡信息");
        List<Tbl_userCard> list = getUserCardList();//获取未上传客户卡信息
        Tbl_userCard userCard=null;
        int operResult=0;
        if(list!=null&&list.size()>0){

            for(int i=0;i<list.size();i++){
                userCard = list.get(i);
                CardUploadRequest localCardUploadRequest = new CardUploadRequest();
                localCardUploadRequest.setId(userCard.getId().trim());//必填
                localCardUploadRequest.setCardType(userCard.getCardType());//必填
                localCardUploadRequest.setBrand(userCard.getBrand());//必填
//				if(userCard.getModel()!=null){
                if(EmptyUtil.isNotEmpty1(userCard.getModel())){
                    try {
                        localCardUploadRequest.setModel(userCard.getModel().trim());//非必填
                    } catch (Exception e) {
                        localCardUploadRequest.setModel("0");//非必填
                        log.info("上传用户卡'"+userCard.getId()+"'填充'卡型号Model'失败，填充默认值'0':"+e.getMessage());
                    }
                }
                localCardUploadRequest.setAgencyId(userCard.getChannelId().trim().substring(0, 11));//必填
                localCardUploadRequest.setUserId(userCard.getUserId().trim());//必填
                localCardUploadRequest.setVehicleId(userCard.getVehicleId().trim());//必填
                localCardUploadRequest.setEnableTime(DateUtil.formatDateTimes(userCard.getEnableTime()));//必填
                if(userCard.getExpireTime().before(userCard.getEnableTime())){//如果失效时间小于生效时间 //必填
                    localCardUploadRequest.setExpireTime(DateUtil.formatDateTimes(new Date()));
                }else{
                    try {
                        localCardUploadRequest.setExpireTime(DateUtil.formatDateTimes(userCard.getExpireTime()));
                    } catch (Exception e) {
                        localCardUploadRequest.setExpireTime(DateUtil.formatDateTimes(new Date()));
                        log.info("上传用户卡'"+userCard.getId()+"'填充'卡到期时间ExpireTime'失败，填充默认值'new Date()':"+e.getMessage());
                    }
                }
                localCardUploadRequest.setIssuedType(userCard.getIssuedType());//必填
                localCardUploadRequest.setChannelId(userCard.getChannelId().trim());//必填
                localCardUploadRequest.setIssuedTime(DateUtil.formatDateTimes(userCard.getIssuedTime()));//必填
                localCardUploadRequest.setStatus(userCard.getStatus());//必填
                if(userCard.getStatusChangeTime()!=null&&!"".equals(userCard.getStatusChangeTime())){
                    try {
                        localCardUploadRequest.setStatusChangeTime(DateUtil.formatDateTimes(userCard.getStatusChangeTime()));//非必填
                    } catch (Exception e) {
                        localCardUploadRequest.setStatusChangeTime(DateUtil.formatDateTimes(new Date()));//非必填
                        log.info("上传用户卡'"+userCard.getId()+"'填充'卡状态变更时间StatusChangeTime'失败，填充默认值'new Date()':"+e.getMessage());
                    }
                }else{
                    localCardUploadRequest.setStatusChangeTime(DateUtil.formatDateTimes(new Date()));//非必填
                }
                localCardUploadRequest.setOperation(userCard.getFlag());//必填 1-新增2-变更3-删除
                //获取发送文件名
                String fileName = ETCCommHelper.getFileName(localCardUploadRequest,"65");
                //生成就json文件
//				CreateFileUtil.createJsonFile(localCardUploadRequest.toJsonStr(), "",fileName);

                try{
                    //指定响应的协议模型,调用upload发送数据
                    CardUploadResponse response =  ETCCommHelper.sdtsUpload(fileName, localCardUploadRequest, CardUploadResponse.class);
                    log.info("上传客户卡信息成功,服务器返回："+response.toJson());
                    if(response!=null&&response.getInfo().equals("成功！")){

                        //上传成功,更新客户卡信息表状态
                        if(localCardUploadRequest.getOperation()!=3){//不是删除操作,变更状态
                            if(userCardDao.updateUploaduserCardflag(userCard.getId())==1){

                                log.info("更新客户卡信息数据成功");

                                operResult ++;

                            }else{

                                log.info("更新客户卡信息数据失败");

                            }
                        }else{//删除操作,删除该条数据

                            if(userCardDao.deleteUploaduserCardflag(userCard.getId())==1){
                                log.info("删除客户卡信息数据成功");
                                operResult ++;
                            }else{

                                log.info("更新客户卡信息数据失败");

                            }

                        }


                    }else{
                        log.info("上传客户卡信息失败,失败信息："+response.getInfo());
                    }

                }catch(IOException e){

                    log.error("上传客户卡信息失败!失败信息："+e.getMessage());

                    continue;

                }catch (ApiRequestException apie) {

                    log.error("上传客户卡信息失败!失败信息："+ apie.getMessage());

                    if(apie.getErrCode()==707){
                        userCardDao.updateUploaduserCardflag(userCard.getId());
                    }else if(apie.getErrCode()==703||apie.getErrCode()==704){
                        userCardDao.updateUploaduserCardflagError(userCard.getId());
                    }

                    continue;

                }
            }
            return "客户卡信息上传结束!";
        }else{

            return "无客户卡信息,上传结束...";
        }

    }
    //获取充值信息
    @SuppressWarnings("unchecked")
    public List<Tbl_userCard> getUserCardList() throws Exception {
        List<Tbl_userCard> list;
        try {
            list = userCardDao.getUnuploaduserCardList();
        } catch (Exception e1) {
            e1.printStackTrace();
            log.error("获取未上传客户卡信息失败!错误信息：", e1);
            throw new Exception("获取未上传客户卡信息失败："+e1.getMessage());
        }
        return list;
    }
}
